
package me.tomato3017.plugins.epicmusic.thread;

import java.util.HashMap;
import me.tomato3017.plugins.epicmusic.EpicMusic;
import me.tomato3017.plugins.epicmusic.region.RegionData;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.event.spout.SpoutCraftEnableEvent;
import org.getspout.spoutapi.player.SpoutPlayer;

/**
 *
 * @author Anthony Kirksey <Anthony.Kirksey@gmail.com>
 * Purpose: Handles all threads associated to spoutclients.
 */
public class ThreadManager {
    EpicMusic plugin;
    
    HashMap<Player, Integer> playerThreadID; //Holds the thread relationship between each player and its thread ID
    HashMap<Integer,PlayerMusicThread> threads; //Holds all executed threads.

    public ThreadManager(EpicMusic plugin) {
        this.plugin = plugin;
        
        playerThreadID = new HashMap<Player, Integer>();
        threads = new HashMap<Integer, PlayerMusicThread>();
    }
    
    public boolean createPlayerThread(Player player){
        if(player instanceof Player){
            RegionData rData = EpicMusic.getRegionManager().GetRegion(player.getLocation());
            
            
            PlayerMusicThread pThread = new PlayerMusicThread(plugin, player, rData);
            
            
            if(EpicMusic.isDEBUG()){
                EpicMusic.debugLog("Creating Music thread for player:" + player.getName());
            }
            int ID = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, pThread, 200, 100);
            playerThreadID.put(player, ID);
            threads.put(ID, pThread);
            
            return true;
        }
        return false;
    }
    
    public void removePlayerThread(Player player){
        if(player instanceof Player){
            SpoutPlayer sp = (SpoutPlayer) player;
            
            if(sp.isSpoutCraftEnabled()){
                int ID = playerThreadID.get(player);

                EpicMusic.debugLog("Removing thread ID:" + ID, 2);
                plugin.getServer().getScheduler().cancelTask(ID);
                playerThreadID.remove(player);
                threads.remove(ID);

                EpicMusic.debugLog("Threads remaining:" + threads.size(), 2);   
            }
        }
    }
    
    public PlayerMusicThread getPlayerThread(Player player){
        if(player instanceof Player){
            if(playerThreadID.containsKey(player)){
                int ID = playerThreadID.get(player);
                
                return threads.get(ID);
            }
        }
        
        return null;
    }
    
}
